package com.dayuanit.dy8.atm.springbootatm.task;

import com.dayuanit.dy8.atm.springbootatm.entity.Transfer;
import com.dayuanit.dy8.atm.springbootatm.mapper.TransferMapper;
import com.dayuanit.dy8.atm.springbootatm.service.BankCardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Component("transferTask")
public class TransferTask {

    @Autowired
    private TransferMapper transferMapper;

    @Autowired
    private BankCardService bankCardService;

    public void doTask() {
//        System.out.println("转账任务 do task ...");
//        processTransfer();
//        processTransfer2();
    }

    private void processTransfer2() {
        // 分页查询待处理的转账订单
        int currentPage = 1;
        int prePageNum = 2;
        int offset = 0;

        final Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND, -60);
        final Date dealTime = instance.getTime();

        do {
            offset = (currentPage - 1) * prePageNum;
            final List<Transfer> transfers = transferMapper.listTransfer(dealTime, 0, offset, 2);

            for (Transfer transfer : transfers) {
                // 处理每一条转账记录
                System.out.println(">>>>转账记录ID=" + transfer.getId());
                try {
                    bankCardService.transferIn2(transfer);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            currentPage ++;
            if (transfers.size() <= 0) {
                break;
            }
        } while(true);
    }

    private void processTransfer() {
        // 分页查询待处理的转账订单
        int currentPage = 1;
        int prePageNum = 2;
        int offset = 0;

        final Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND, -60);
        final Date dealTime = instance.getTime();

        do {
            offset = (currentPage - 1) * prePageNum;
            final List<Transfer> transfers = transferMapper.listTransfer(dealTime, 0, offset, 2);

            for (Transfer transfer : transfers) {
                // 处理每一条转账记录
                System.out.println(">>>>转账记录ID=" + transfer.getId());
                try {
                    bankCardService.transferIn(transfer);
                } catch (Exception e) {
                    e.printStackTrace();
                    // 修改订单状态为待返回
                    transferMapper.updateStatus(transfer.getId(), transfer.getStatus(), 2);
                }
            }

            currentPage ++;
            if (transfers.size() <= 0) {
                break;
            }
        } while(true);

    }
}
